package com.kqkj.dyrule.marketing.querier;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class HbaseQuerier {
    Table table;
    String familyName;
    public HbaseQuerier(Connection conn,String tableName,String familyName) throws IOException {
        table = conn.getTable(TableName.valueOf(tableName));
        this.familyName = familyName;
    }

    /**
     * 从hbase查询画像条件是否满足
     * @param profileConditions 画像条件
     * @param deviceId
     * @return
     * @throws IOException
     */
    public boolean queryProfileConditionIsMatch(Map<String,String> profileConditions,String deviceId) throws IOException {
        Get get = new Get(Bytes.toBytes(deviceId));
        Set<String> tags = profileConditions.keySet();
        for (String tag : tags) {
            get.addColumn(Bytes.toBytes(familyName),Bytes.toBytes(tag));
        }
        //执行get查询
        Result result = table.get(get);
        for (String tag : tags) {
            byte[] v = result.getValue(familyName.getBytes(), tag.getBytes());
            String value = new String(v);
            if (StringUtils.isBlank(value) || !profileConditions.get(tag).equals(value)) return false;
        }
        return true;

    }
}
